import Vue from 'vue'
import VueRouter from 'vue-router'
import routeInfo from './route'
import store from '@/store'

Vue.use(VueRouter)
const index = () => import('../views/index.vue')
const login = () => import('../views/login.vue')
const {authorizes,menus,permission,roles,personal_password,personal_data,home} = routeInfo
let routerList = [home,personal_password,personal_data]
if (process.env.NODE_ENV === 'development') {   //调试页面
  routerList = [...routerList, authorizes,menus,permission,roles]
}

const routes = [
  {
    path: '/',
    component: index,
    redirect:'home',
    children:[]
  }, {
    path: '/login',
    component: login,
    meta: {
        requireAuth: false
    }
  },
]

// const createRouter = () => new VueRouter({
//   mode: 'history',
//   routes
// })
// const router = createRouter();
const router = new VueRouter({
  mode: 'history',
  routes
})



export function initDynamicRoutes () {
  // 根据二级权限 对路由规则进行动态的添加
  // router.matcher = createRouter().matcher;   //好像不太好使
  const currentRoutes = router.options.routes
  currentRoutes[0].children = []
  const rightList = store.state.rightList
  rightList.forEach(item => {
    if(item.sub_menus.length > 0){ 
      item.sub_menus.forEach(v => {
        /**
         * 添加 二级路由
         * 不想嵌套三级路由，直接挂载到一级路由上   
         */
        const temp = routeInfo[v.route.replace(/\//,'_')]
        if(temp) currentRoutes[0].children.push(temp)
      });
    }
  })
  currentRoutes[0].children.push(...routerList)
  // '/'重定向的路由
  // let path = currentRoutes[0].children.length > 0 ? currentRoutes[0].children[0].path : ""
  // currentRoutes[0].redirect = path ? '/' + path : ''
  currentRoutes[2] = routeInfo.notFound
  // console.log('currentRoutes',currentRoutes)
  router.addRoutes(currentRoutes)
}

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)

}

export default router

